const express = require("express");
const router = express.Router();
const { Article } = require("../../models/article");
const { Op } = require("sequelize");
const { NotFoundError, success, failure } = require("../../utils/response");
/**
 * 查询文章列表
 * GET /admin/articles
 * */
router.get("/", async function (req, res, next) {
    try {
        const query = res.query;
        // 当前是第几页, 如果不传， 默认第一页
        const page = Number(query.page) || 1;
        // 每页显示多少条数据，如果不传，那就显示10条
        const pageSize = Number(query.pageSize) || 10;
        // 计算 offset
        const offset = (page - 1) * pageSize;
        const condition = {
            order: [["id", "DESC"]],
            limit: pageSize,
            offset: offset,
        };
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`,
                },
            };
        }
        const { count, rows } = await Article.findAndCountAll(condition);
        success(res, '查询文章列表成功', {
            articles: rows,
            pagination: {
                total: count,
                page,
                pageSize,
            },
        });

    } catch (error) {
        failure(res, error);
    }
});
/**
 * 查询文章详情
 * GET /admin/articles/:id
 * */
router.get("/:id", async function (req, res, next) {
    try {
        const article = await getArticle(req);
        success(res, "查询文章成功", { article });
    } catch (error) {
        failure(res, error);
    }
});
/**
 * 创建文章
 * GET /admin/articles
 * */
router.post("/", async function (req, res, next) {
    try {
        const params = filterBody(req);
        const article = await Article.create(params);
        success(res, "创建文章成功", { article }, 201);
    } catch (error) {
        failure(res, error);
    }
});
/**
 * 删除文章详情
 * Delete /admin/articles/:id
 * */
router.delete("/:id", async function (req, res, next) {
    try {
        const article = await getArticle(req);
        await article.destroy();
        success(res, "删除文章成功");
    } catch (error) {
        failure(res, error);
    }
});
/**
 * 更新文章
 * PUT /admin/articles/:id
 * */
router.put("/:id", async function (req, res, next) {
    try {
        const article = await getArticle(req);
        const body = filterBody(req);
        await article.update(body);
        success(res, "更新文章成功", { article });
    } catch (error) {
        failure(res, error);
    }
});
/**
 * 查询当前文章
 * */
const getArticle = async (req) => {
    const { id } = req.params;
    const article = await Article.findByPk(id);
    if (!article) {
        throw new NotFoundError(`ID: ${id} 的文章未找到`);
    }
    return article;
}
/**
 * 白名单过滤
 * @param req
 * @returns {{ title, content: {string | string | *}}}
 * */
const filterBody = (req) => {
    return {
        title: req.body.title,
        content: req.body.content,
    };
};

module.exports = router;
